'''
Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
Date: 2025-09-03 23:02:35
LastEditors: duliang thinktanker@163.com
LastEditTime: 2025-09-04 23:34:13
FilePath: \rtsp-image-transfer\temp.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE

'''
import json
import cv2
import numpy as np

name_list = ["清污机2", "1#"]
with open("./config/rtsplist.json", "r", encoding="utf8") as f:
    rtsp_list = json.load(f)
    print("Available streams:", list(rtsp_list.keys()))

# 创建视频捕获对象列表
caps = []
stream_names = []
for name, rtsp_url in rtsp_list.items():
    if name not in name_list:
        continue
    cap = cv2.VideoCapture(rtsp_url[0], cv2.CAP_FFMPEG)
    cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
    caps.append((cap, name))
    stream_names.append(name)

size = (640, 480)
cols = 2  # 每行显示的视频数量
rows = (len(caps) + cols - 1) // cols  # 计算需要的行数

# 创建全屏窗口
cv2.namedWindow('RTSP Streams', cv2.WINDOW_NORMAL)
cv2.setWindowProperty('RTSP Streams', cv2.WND_PROP_FULLSCREEN,
                      cv2.WINDOW_FULLSCREEN)

while True:
    frames = []
    # 读取所有流的帧
    for cap, name in caps:
        ret, frame = cap.read()
        if not ret:
            print(
                f"Error: Can't receive frame from {name} (stream end?). Using blank frame."
            )
            frame = np.zeros((size[1], size[0], 3), dtype=np.uint8)
            cv2.putText(frame, f"No Signal: {name}", (10, size[1] // 2),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
        else:
            frame = cv2.resize(frame, size)
            # 在帧上添加流名称
            cv2.putText(frame, name, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1,
                        (0, 255, 0), 2)
        frames.append(frame)

    # 如果帧数不足网格大小，用黑色帧填充
    while len(frames) < rows * cols:
        blank_frame = np.zeros((size[1], size[0], 3), dtype=np.uint8)
        frames.append(blank_frame)

    # 将帧组合成网格
    rows_frames = []
    for i in range(rows):
        row_frames = frames[i * cols:(i + 1) * cols]
        row_frame = np.hstack(row_frames)
        rows_frames.append(row_frame)

    # 垂直堆叠所有行
    combined_frame = np.vstack(rows_frames)

    # 显示组合帧
    cv2.imshow('RTSP Streams', combined_frame)

    # 按 'q' 键退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放所有 VideoCapture 对象并关闭所有 OpenCV 窗口
for cap, name in caps:
    cap.release()
cv2.destroyAllWindows()
